package com.liuyi.netty.im.lychat.modular.service.impl;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuyi.netty.im.commons.codes.CodeConst;
import com.liuyi.netty.im.lychat.LychatConst;
import com.liuyi.netty.im.lychat.modular.caches.UserCache;
import com.liuyi.netty.im.lychat.modular.caches.UserFriendCache;
import com.liuyi.netty.im.lychat.modular.entity.User;
import com.liuyi.netty.im.lychat.modular.entity.UserFriend;
import com.liuyi.netty.im.lychat.modular.enums.MessageReminding;
import com.liuyi.netty.im.lychat.modular.mapper.UserFriendMapper;
import com.liuyi.netty.im.lychat.modular.service.IChatSessionService;
import com.liuyi.netty.im.lychat.modular.service.IUserFriendService;
import com.liuyi.netty.im.lychat.modular.service.IUserService;
import com.liuyi.netty.im.server.util.ImHelp;
import com.liuyi.rapid.develop.tool.unusual.BizException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * <p>
 * 用户好友表 服务实现类
 * </p>
 *
 * @author mybatis-plus
 * @since 2021-12-29
 */
@Service
public class UserFriendServiceImpl extends ServiceImpl<UserFriendMapper, UserFriend> implements IUserFriendService {

    @Resource
    private IUserService userServicel;
    @Resource
    private IChatSessionService chatSessionService;
    @Resource
    private UserFriendCache cache;

    @Override
    public UserFriendCache cache() {
        return cache;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void delFriend(String userId, String friendUserId) {
        this.remove(q().eq(UserFriend.USER_ID, userId).eq(UserFriend.FRIEND_USER_ID, friendUserId));
        this.remove(q().eq(UserFriend.USER_ID, friendUserId).eq(UserFriend.FRIEND_USER_ID, userId));
        cache().removeUserIdAndFriendUserId(userId, friendUserId);
        chatSessionService.removeSession(userId, ImHelp.sessionId(CodeConst.SessionType.C2C, friendUserId));
        chatSessionService.removeSession(friendUserId, ImHelp.sessionId(CodeConst.SessionType.C2C, userId));
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void createFriend(String userId, String friendUserId, boolean twoway) {
        UserCache userCache = userServicel.cache();
        User friendUser = userCache.getById(friendUserId);
        if (friendUser == null) {
            throw new BizException("抱歉，对方不存在");
        }
        if (checkFriend(userId, friendUserId)) {
            throw new BizException("抱歉，对方已是您的好友");
        }
        if (count(q().eq(UserFriend.USER_ID, userId).eq(UserFriend.FRIEND_USER_ID, friendUserId)) > 0) {
            throw new BizException("抱歉，对方已是您的好友");
        }
        this.save(new UserFriend().setUserId(userId).setFriendUserId(friendUserId)
                .setFriendMemo(friendUser.getNick())
                .setMessageReminding(MessageReminding.RECEIVE_AND_REMIND));
        if (twoway && !userId.equals(friendUserId)) {
            User user = userCache.getById(userId);
            this.save(new UserFriend().setUserId(friendUserId).setFriendUserId(userId)
                    .setFriendMemo(user.getNick())
                    .setMessageReminding(MessageReminding.RECEIVE_AND_REMIND));
        }
    }

    @Override
    public void wrapper(UserFriend userFriend) {
        if (userFriend == null) {
            return;
        }
        User user = userServicel.cache().getById(userFriend.getFriendUserId());
        if (user != null) {
            userFriend.setFriendHead(user.getHead());
        }
    }

    @Override
    public Object c2cProfile(String userId, String fiendUserId) {
        if (StrUtil.isEmpty(userId) || StrUtil.isEmpty(fiendUserId)) {
            return null;
        }
        if (userId.equals(fiendUserId)) {
            User user = userServicel.cache().getById(userId);
            if (user == null) {
                return MapBuilder.create(new HashMap<String, Object>())
                        .put("fromNick", "未知")
                        .put("fromHead", LychatConst.DEFAULT_USER_HEAD).build();
            }
            return MapBuilder.create(new HashMap<String, Object>())
                    .put("fromNick", user.getNick())
                    .put("fromHead", user.getHead()).build();
        } else {
            UserFriend userFriend = cache().getByUserIdAndFriendUserId(fiendUserId, userId);
            if (userFriend == null) {
                User user = userServicel.cache().getById(userId);
                if (user == null) {
                    return MapBuilder.create(new HashMap<String, Object>())
                            .put("fromNick", "未知")
                            .put("fromHead", LychatConst.DEFAULT_USER_HEAD).build();
                }
                return MapBuilder.create(new HashMap<String, Object>())
                        .put("fromNick", user.getNick())
                        .put("fromHead", user.getHead()).build();
            }
            return MapBuilder.create(new HashMap<String, Object>())
                    .put("fromNick", userFriend.getFriendMemo())
                    .put("fromHead", userFriend.getFriendHead()).build();
        }

    }
}
